package com.ygqh.baby.controller.admin;

import java.math.BigDecimal;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.stream.Collectors;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ygqh.baby.ao.CheckStatus;
import com.ygqh.baby.ao.Message;
import com.ygqh.baby.ao.UserType;
import com.ygqh.baby.po.YgAgent;
import com.ygqh.baby.po.YgUser;
import com.ygqh.baby.po.YgUserCultivationDay;
import com.ygqh.baby.service.YgAgentInviteRecordService;
import com.ygqh.baby.service.YgAgentService;
import com.ygqh.baby.service.YgUserCultivationDayService;
import com.ygqh.baby.service.YgUserService;
import com.ygqh.baby.utils.DateConvertUtils;

@Controller
@RequestMapping("/admin/agentTemp")
public class AgentTempController extends BaseController<Object, java.lang.Long> {

	@Autowired
	private YgAgentService ygAgentService;
	@Autowired
	private YgUserCultivationDayService ygUserCultivationDayService;
	@Autowired
	private YgAgentInviteRecordService ygAgentInviteRecordService;
	@Autowired
	private YgUserService ygUserService;

	@RequestMapping("cancelBatch")
	@ResponseBody
	public Message cancelBatch(@RequestParam(required = true) String token) throws ParseException {
		if (StringUtils.isBlank(token)) {
			return Message.error("没有权限", null);
		}
		Date startDate = DateConvertUtils.parse("2017-04-01", DateConvertUtils.DATE_FORMAT);
		Date endDate = DateConvertUtils.parse("2017-11-01", DateConvertUtils.DATE_FORMAT);
		List<YgAgent> list = ygAgentService.findAgentByTime(startDate, endDate, CheckStatus.Pass);

		Map<String, BigDecimal> cancelData = new HashMap<>();
		Map<String, BigDecimal> notCancelData = new HashMap<>();
		/*List<String> cancelList = new ArrayList<>();
		List<String> notCancelList = new ArrayList<>();*/
		Map<String, List<YgAgent>> map = list.stream().collect(Collectors.groupingBy(YgAgent::getPassTimeMonthStr));
		/*ExecutorService threadPool = Executors.newFixedThreadPool(5);*/
		for (Entry<String, List<YgAgent>> entry : map.entrySet()) {
			String month = entry.getKey();
			List<YgAgent> agentList = entry.getValue();
			Date start = null;
			Date end = null;
			switch (month) {
			case "2017-04":
				start = DateConvertUtils.parse("2018-02-01", DateConvertUtils.DATE_FORMAT);
				end = DateConvertUtils.parse("2018-05-01", DateConvertUtils.DATE_FORMAT);
				break;
			case "2017-05":
				/*start = DateConvertUtils.parse("2017-12-01", DateConvertUtils.DATE_FORMAT);
				end = DateConvertUtils.parse("2018-03-01", DateConvertUtils.DATE_FORMAT);
				break;*/
				continue;
			case "2017-06":
				start = DateConvertUtils.parse("2018-01-01", DateConvertUtils.DATE_FORMAT);
				end = DateConvertUtils.parse("2018-04-01", DateConvertUtils.DATE_FORMAT);
				break;
			case "2017-07":
				start = DateConvertUtils.parse("2018-02-01", DateConvertUtils.DATE_FORMAT);
				end = DateConvertUtils.parse("2018-05-01", DateConvertUtils.DATE_FORMAT);
				break;
			case "2017-08":
				/*start = DateConvertUtils.parse("2017-12-01", DateConvertUtils.DATE_FORMAT);
				end = DateConvertUtils.parse("2018-03-01", DateConvertUtils.DATE_FORMAT);
				break;*/
				continue;
			case "2017-09":
				start = DateConvertUtils.parse("2018-01-01", DateConvertUtils.DATE_FORMAT);
				end = DateConvertUtils.parse("2018-04-01", DateConvertUtils.DATE_FORMAT);
				break;
			case "2017-10":
				start = DateConvertUtils.parse("2018-02-01", DateConvertUtils.DATE_FORMAT);
				end = DateConvertUtils.parse("2018-05-01", DateConvertUtils.DATE_FORMAT);
				break;
			}
			if (start != null) {
				for (YgAgent ygAgent : agentList) {
					if (!ygAgent.getUserType().equals(UserType.UserAgent)) {
						continue;
					}

					List<YgUserCultivationDay> priceList = ygUserCultivationDayService.getSumGroupByMonth(start, end, ygAgent.getUserId());
					/*Boolean cancel = true;
					for (YgUserCultivationDay m : priceList) {
						if (m.getTotalPrice().compareTo(new BigDecimal("1000")) >= 0) {
							System.out.println(ygAgent.getUserId() + "===============" + m.getTotalPrice() + "===============" + month);
							cancel = false;
							notCancelList.add(ygAgent.getUserId().toString());
						}
					}
					if (cancel) {
						String str = ygAgent.getUserId().toString();
						cancelList.add(str);

						threadPool.execute(new Runnable() {
							public void run() {
								Message message = ygAgentService.updateYgAgent(ygAgent.getUserId(), "系统", UserType.UserAgent);
								if (message.getType().equals(Message.Type.success)) {
									message = wxMpMessageService.cancelAgentAuditMsg(null, ygAgent.getYgUser().getOpenId(), "您好，您的代理资格将在5天后取消，有疑问请联系客服。",
											"/channel/index.html?usertype=UserAgent");
								}
							}
						});
					}*/
					if (CollectionUtils.isEmpty(priceList)) {
						cancelData.put(ygAgent.getTelPhone(), new BigDecimal("0.00"));
						continue;
					}
					BigDecimal totalPrice = priceList.stream().map(o -> o.getTotalPrice()).reduce((p1, p2) -> p1.add(p2)).get();
					if (totalPrice != null && totalPrice.compareTo(new BigDecimal("2000")) >= 0) {
						notCancelData.put(ygAgent.getTelPhone(), totalPrice);
					} else {
						cancelData.put(ygAgent.getTelPhone(), totalPrice);
					}
				}
			}
		}
		/*threadPool.shutdown();*/
		Map<String, Object> result = new HashMap<>();
		result.put("cancel", cancelData);
		result.put("notCancel", notCancelData);
		return Message.success(result);
	}

	@RequestMapping("rechargeNewAgentByVip")
	@ResponseBody
	public Message rechargeNewAgentByVip() {
		List<YgUser> userList = ygUserService.findByLevel(10);
		if (CollectionUtils.isEmpty(userList)) {
			return SUCCESS_MESSAGE;
		}
		System.out.println("女王总数：" + userList.size());
		int count = 0;
		List<Long> errorList = new ArrayList<Long>();
		for (YgUser ygUser : userList) {
			if (ygUser.isUserAgent()) { // 过滤已成为代理的用户
				continue;
			}
			try {
				ygAgentInviteRecordService.rechargeUserAgentRightNow(ygUser.getId(), Boolean.FALSE);
			} catch (Exception e) {
				e.printStackTrace();
				errorList.add(ygUser.getId());
			}
			count ++;
		}
		System.out.println("共操作女王数：" + count);
		System.out.println("操作错误：" + errorList.toString());
		return SUCCESS_MESSAGE;
	}
	
}
